<template>
  <!-- 登录 -->
  <div class="login w-full h-full">
    <el-form
      ref="formRef"
      class="w-[320px] p-10 absolute top-[40%] -translate-y-1/2 left-20"
      :model="form"
      :rules="rules"
      label-position="top"
    >
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="form.password"
          placeholder="请输入密码"
        />
      </el-form-item>
      <el-form-item>
        <div class="w-full relative">
          <router-link
            to="/updatePassword"
            class="block text-blue-400 text-right mb-2">
            修改密码
          </router-link>
          <el-button class="flex-1 w-full" type="primary" @click="handleLogin">
            登录
          </el-button>
          <router-link
            to="/register"
            class="block text-blue-700 text-right mb-2"
          >
            立即注册
          </router-link>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { ElMessage, type FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import { request } from "../../utils/request";
import { getUserInfo, login } from "../../api";
import { useRouter } from "vue-router";
import { useUserStore } from "../../store/user";

interface Form {
  account: string;
  password: string;
}

const form = reactive<Form>({
  account: "",
  password: "",
});
const rules = {
  account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" },
  ],
};
const router = useRouter();
const formRef = ref<FormInstance>();
const { setUserInfo } = useUserStore();
function handleLogin() {
  formRef.value?.validate((valid) => {
    if (!valid) return;
    request({
      fn: login,
      params: [form],
      success(res: any) {
        localStorage.setItem("token", res.data);
        ElMessage.success("登录成功");
        getInfo();
      },
    });
  });
}

function getInfo() {
  request({
    fn: getUserInfo,
    params: [],
    success(res: any) {
      const role = res.data.role;
      setUserInfo(res.data);
      if (role === "TEACHER") {
        router.push("/teacher");
      } else {
        router.push("/student");
      }
    },
  });
}
</script>
<style scoped lang="scss">
.login {
  background: url("../../assets/images/login_bg.png") no-repeat center center;
  background-size: cover;
}
</style>
